<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 对话助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 900px;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: 90vh;
        }

        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 30px;
            text-align: center;
        }

        .chat-header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .chat-header .memory-info {
            font-size: 12px;
            margin-top: 5px;
            opacity: 0.9;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px 30px;
            background: #f5f7fa;
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            animation: fadeIn 0.3s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 18px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.5;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-bottom-right-radius: 4px;
        }

        .message.ai .message-content {
            background: white;
            color: #333;
            border-bottom-left-radius: 4px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .message.ai .message-content code {
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
            font-size: 0.9em;
            color: #c7254e;
        }

        .message.ai .message-content strong {
            font-weight: 600;
            color: #2c3e50;
        }

        .message.ai .message-content em {
            font-style: italic;
            color: #34495e;
        }

        .message.ai .message-content ul {
            margin: 8px 0;
            padding-left: 20px;
            list-style-type: disc;
        }

        .message.ai .message-content li {
            margin: 4px 0;
            line-height: 1.6;
        }

        .message.ai .message-content p {
            margin: 8px 0;
        }

        .message.ai .message-content h1,
        .message.ai .message-content h2,
        .message.ai .message-content h3,
        .message.ai .message-content h4 {
            margin: 12px 0 8px 0;
            font-weight: 600;
        }

        .message.ai .message-content h1 {
            font-size: 1.5em;
            border-bottom: 2px solid #eee;
            padding-bottom: 4px;
        }

        .message.ai .message-content h2 {
            font-size: 1.3em;
        }

        .message.ai .message-content h3 {
            font-size: 1.1em;
        }

        .message-info {
            font-size: 11px;
            color: #666;
            margin-bottom: 5px;
            padding: 0 5px;
        }

        .chat-input-container {
            padding: 20px 30px;
            background: white;
            border-top: 1px solid #e0e0e0;
        }

        .input-wrapper {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }

        #messageInput {
            flex: 1;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            padding: 12px 16px;
            font-size: 15px;
            font-family: inherit;
            resize: none;
            min-height: 50px;
            max-height: 120px;
            transition: border-color 0.3s;
        }

        #messageInput:focus {
            outline: none;
            border-color: #667eea;
        }

        #sendButton {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            padding: 12px 30px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            white-space: nowrap;
        }

        #sendButton:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        #sendButton:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        .loading-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top-color: white;
            border-radius: 50%;
            animation: spin 0.6s linear infinite;
            margin-left: 8px;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        .typing-indicator {
            display: inline-flex;
            gap: 4px;
            padding: 8px 0;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: #999;
            border-radius: 50%;
            animation: bounce 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(1) {
            animation-delay: -0.32s;
        }

        .typing-dot:nth-child(2) {
            animation-delay: -0.16s;
        }

        @keyframes bounce {
            0%, 80%, 100% {
                transform: scale(0);
            }
            40% {
                transform: scale(1);
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h1>AI 对话助手</h1>
            <div class="memory-info">Memory ID: <span id="memoryIdDisplay">未初始化</span></div>
        </div>

        <div class="chat-messages" id="chatMessages">
            <div class="message ai">
                <div>
                    <div class="message-info">AI 助手</div>
                    <div class="message-content">你好！我是 AI 助手，有什么可以帮助你的吗？</div>
                </div>
            </div>
        </div>

        <div class="chat-input-container">
            <div class="input-wrapper">
                <textarea 
                    id="messageInput" 
                    placeholder="输入你的问题..." 
                    rows="1"
                ></textarea>
                <button id="sendButton">发送</button>
            </div>
        </div>
    </div>

    <script>
        // 生成唯一的内存 ID
        let memoryId = localStorage.getItem('memoryId') || generateMemoryId();
        if (!localStorage.getItem('memoryId')) {
            localStorage.setItem('memoryId', memoryId);
        }
        document.getElementById('memoryIdDisplay').textContent = memoryId;

        function generateMemoryId() {
            return 'mem_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        }

        const chatMessages = document.getElementById('chatMessages');
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        let isLoading = false;
        let currentAiMessage = null;

        // 自动调整输入框高度
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = this.scrollHeight + 'px';
        });

        // Enter 发送消息
        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 发送消息
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (!message || isLoading) return;

            // 添加用户消息到界面
            addMessage('user', message);
            messageInput.value = '';
            messageInput.style.height = 'auto';
            
            isLoading = true;
            sendButton.disabled = true;
            sendButton.innerHTML = '发送中<span class="loading-indicator"></span>';

            try {
                await fetchWithStream(message);
            } catch (error) {
                console.error('Error:', error);
                addMessage('ai', '抱歉，发生了错误：' + error.message);
            } finally {
                isLoading = false;
                sendButton.disabled = false;
                sendButton.innerHTML = '发送';
                messageInput.focus();
            }
        }

        // 使用 Fetch API 处理流式响应
        async function fetchWithStream(message) {
            // 创建 AI 消息容器
            const aiMessageDiv = document.createElement('div');
            aiMessageDiv.className = 'message ai';
            aiMessageDiv.innerHTML = `
                <div>
                    <div class="message-info">AI 助手</div>
                    <div class="message-content"></div>
                </div>
            `;
            chatMessages.appendChild(aiMessageDiv);
            currentAiMessage = aiMessageDiv.querySelector('.message-content');

            const url = `/chat/memory?memoryId=${encodeURIComponent(memoryId)}&message=${encodeURIComponent(message)}`;
            
            try {
                const response = await fetch(url);
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let buffer = '';

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop(); // 保留最后一个不完整的行

                    for (const line of lines) {
                        if (line.trim()) {
                            // 追加内容到当前消息，使用累加的原始文本
                            if (currentAiMessage) {
                                currentAiMessage.dataset.rawText = (currentAiMessage.dataset.rawText || '') + line + '\n';
                                currentAiMessage.innerHTML = formatFullContent(currentAiMessage.dataset.rawText);
                            }
                            // 滚动到底部
                            chatMessages.scrollTop = chatMessages.scrollHeight;
                        }
                    }
                }

                // 处理剩余的缓冲区内容
                if (buffer.trim() && currentAiMessage) {
                    currentAiMessage.dataset.rawText = (currentAiMessage.dataset.rawText || '') + buffer + '\n';
                    currentAiMessage.innerHTML = formatFullContent(currentAiMessage.dataset.rawText);
                    chatMessages.scrollTop = chatMessages.scrollHeight;
                }
            } catch (error) {
                throw new Error('网络请求失败');
            }
        }

        function addMessage(type, content) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}`;
            
            const sender = type === 'user' ? '你' : 'AI 助手';
            messageDiv.innerHTML = `
                <div>
                    <div class="message-info">${sender}</div>
                    <div class="message-content">${escapeHtml(content)}</div>
                </div>
            `;
            
            chatMessages.appendChild(messageDiv);
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 格式化完整内容，支持基本 Markdown 排版
        function formatFullContent(text) {
            if (!text) return '';
            
            // 转义 HTML 特殊字符
            let formatted = text
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;');
            
            // 处理代码块（```language\ncode```）
            formatted = formatted.replace(/```(\w+)?\n?([\s\S]*?)```/g, function(match, lang, code) {
                const escapedCode = code.trim();
                return `<div style="background: #f5f5f5; border: 1px solid #ddd; border-radius: 6px; padding: 12px; margin: 8px 0; overflow-x: auto; font-family: 'Consolas', 'Monaco', monospace; font-size: 0.9em; white-space: pre;">${escapedCode}</div>`;
            });
            
            // 处理行内代码 `code`
            formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>');
            
            // 处理粗体 **text**
            formatted = formatted.replace(/\*\*([^*]+?)\*\*/g, '<strong>$1</strong>');
            
            // 处理斜体 *text*（排除前面刚匹配的**）
            formatted = formatted.replace(/\*([^*\s]+(?:\s+[^*\s]+)*?)\*/g, '<em>$1</em>');
            
            // 按行处理标题和列表
            const lines = formatted.split('\n');
            let result = [];
            let inList = false;
            
            for (const line of lines) {
                const trimmedLine = line.trim();
                
                // 处理标题
                if (trimmedLine.startsWith('###')) {
                    if (inList) {
                        result.push('</ul>');
                        inList = false;
                    }
                    result.push('<h3>' + trimmedLine.substring(3).trim() + '</h3>');
                } else if (trimmedLine.startsWith('##')) {
                    if (inList) {
                        result.push('</ul>');
                        inList = false;
                    }
                    result.push('<h2>' + trimmedLine.substring(2).trim() + '</h2>');
                } else if (trimmedLine.startsWith('#')) {
                    if (inList) {
                        result.push('</ul>');
                        inList = false;
                    }
                    result.push('<h1>' + trimmedLine.substring(1).trim() + '</h1>');
                } 
                // 处理列表
                else if (/^[-•*]\s+/.test(trimmedLine)) {
                    if (!inList) {
                        result.push('<ul style="margin: 8px 0 8px 20px; list-style-type: disc;">');
                        inList = true;
                    }
                    result.push('<li>' + trimmedLine.replace(/^[-•*]\s+/, '') + '</li>');
                } 
                // 普通文本行
                else {
                    if (inList) {
                        result.push('</ul>');
                        inList = false;
                    }
                    if (trimmedLine) {
                        result.push(trimmedLine);
                    }
                }
            }
            
            if (inList) {
                result.push('</ul>');
            }
            
            formatted = result.join('\n');
            
            // 转换换行符为 <br>（但保留已有的HTML标签）
            formatted = formatted.replace(/\n/g, '<br>');
            
            return formatted;
        }

        // 绑定发送按钮点击事件
        sendButton.addEventListener('click', sendMessage);
    </script>
</body>
</html>

